/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package beans.managed;

import beans.ejb.FantasydraftresultFacade;
import beans.ejb.FantasyleagueFacade;
import beans.ejb.FantasymatchFacade;
import beans.ejb.FantasyrosterperweekFacade;
import beans.ejb.FantasyteamFacade;
import beans.ejb.NflplayerFacade;
import beans.ejb.NflplayerseasonstatFacade;
import beans.ejb.WeekFacade;
import customEneities.Pair;
import entities.Fantasydraftresult;
import entities.Fantasyleague;
import entities.Fantasymatch;
import entities.Fantasyrosterperweek;
import entities.Fantasyteam;
import entities.Fantasyuser;
import entities.Nflplayer;
import entities.Nflplayerseasonstat;
import entities.Week;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import javax.ejb.EJB;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.SessionScoped;
import javax.faces.component.html.HtmlDataTable;
import javax.faces.context.FacesContext;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

/**
 *
 * @author The Lunatics
 */
@ManagedBean
@SessionScoped
public class LeagueDraftBean implements Serializable {

    @EJB
    private NflplayerFacade nflplayerFacade;
    @EJB
    private FantasydraftresultFacade fantasydraftresultFacade;
    @EJB
    private FantasyteamFacade fantasyteamFacade;
    @EJB
    private FantasyleagueFacade fantasyleagueFacade;
    @EJB
    private NflplayerseasonstatFacade nflplayerseasonstatFacade;
    @EJB
    private FantasymatchFacade fantasymatchFacade;
    @EJB
    private WeekFacade weekFacade;
    @EJB
    private FantasyrosterperweekFacade fantasyrosterperweekFacade;
            
    private Fantasyleague league = null;
    private List<Fantasyteam> teams = null;
    private List<Fantasyteam> reversedTeams = new ArrayList<Fantasyteam>();
    private int currentRound;
    private int currentPick;
    private Fantasyteam currentDraftTeam = null;
    private Fantasyteam selectedTeam;
    private Nflplayer selectedPlayer = null;
    private Nflplayerseasonstat selectedplayerstat = null;
    private HtmlDataTable dataTable;
    private HtmlDataTable teamTable;
    private HtmlDataTable roundTable;
    private List<Integer> roundNumberList = new ArrayList<Integer>(Arrays.asList(1,2,3,4,5,6,7,8,9,10,11,12,13,14,15));

    public List<Integer> getRoundNumberList() {
        return roundNumberList;
    }

    public void setRoundNumberList(List<Integer> roundNumberList) {
        this.roundNumberList = roundNumberList;
    }
    public HtmlDataTable getTeamTable() {
        return teamTable;
    }

    public void setTeamTable(HtmlDataTable teamTable) {
        this.teamTable = teamTable;
    }
    private List<List<Fantasyteam>> roundList = new ArrayList<List<Fantasyteam>>();
    private List<List<Fantasydraftresult>> draftHistory = new ArrayList<List<Fantasydraftresult>>();
    private List<List<Fantasydraftresult>> draftTeamHistory = new ArrayList<List<Fantasydraftresult>>();
    private int round = 15;
    private int roundNumber = 0;
    private int pickNumber = 0;
    private int numberInRound = 0;
    private int getteamname=0;
    private int selectedRound=0;
    private List<Pair> joinplayerandstat = new ArrayList<Pair>();
    private Fantasydraftresult draftResult;
    private List<Nflplayer> players;

    public boolean isDisableBTN() {
        int remainDraft = 15;
        int essentialPOS = 9;
        boolean[] posArray = new boolean[9];
        List<Fantasydraftresult> draftresultbyleagueIdteamId = fantasydraftresultFacade.findDraftResultByLeagueIdTeamId(league, currentDraftTeam);
        remainDraft -= draftresultbyleagueIdteamId.size();
        
        Iterator<Fantasydraftresult> itr = draftresultbyleagueIdteamId.iterator();
        while(itr.hasNext()){
            Nflplayer tmp = itr.next().getPlayerId();
            if("QB".equals(tmp.getPosition()) && !posArray[0]){
                essentialPOS--;
                posArray[0]=true;
            }else if("RB".equals(tmp.getPosition()) && !posArray[1]){
                essentialPOS--;
                posArray[1]=true;
            }else if("RB".equals(tmp.getPosition()) && !posArray[2]){
                essentialPOS--;
                posArray[2]=true;
            }else if("WR".equals(tmp.getPosition()) && !posArray[3]){
                essentialPOS--;
                posArray[3]=true;
            }else if("WR".equals(tmp.getPosition()) && !posArray[4]){
                essentialPOS--;
                posArray[4]=true;
            }else if("TE".equals(tmp.getPosition()) && !posArray[5]){
                essentialPOS--;
                posArray[5]=true;
            }else if(("WR".equals(tmp.getPosition())||"RB".equals(tmp.getPosition()))&& !posArray[6]){
                essentialPOS--;
                posArray[6]=true;
            }else if("K".equals(tmp.getPosition()) && !posArray[7]){
                essentialPOS--;
                posArray[7]=true;
            }else if("DE".equals(tmp.getPosition()) && !posArray[8]){
                essentialPOS--;
                posArray[8]=true;
            }
        }
        System.out.println("remainDraft:"+remainDraft);
        System.out.println("essentialPOS:"+essentialPOS);
        if(selectedPlayer==null){
            return true;
        }
        if(remainDraft>essentialPOS){
            return false;
        }else if(remainDraft==essentialPOS){
            if("QB".equals(selectedPlayer.getPosition()) && !posArray[0]){
                return false;
            }else if("RB".equals(selectedPlayer.getPosition()) && !posArray[1]){
                return false;
            }else if("RB".equals(selectedPlayer.getPosition()) && !posArray[2]){
                return false;
            }else if("WR".equals(selectedPlayer.getPosition()) && !posArray[3]){
                return false;
            }else if("WR".equals(selectedPlayer.getPosition()) && !posArray[4]){
                return false;
            }else if("TE".equals(selectedPlayer.getPosition()) && !posArray[5]){
                return false;
            }else if(("WR".equals(selectedPlayer.getPosition())||"RB".equals(selectedPlayer.getPosition()))&& !posArray[6]){
                return false;
            }else if("K".equals(selectedPlayer.getPosition()) && !posArray[7]){
                return false;
            }else if("DE".equals(selectedPlayer.getPosition()) && !posArray[8]){
                return false;
            }else{
                return true;
            }
        }else{
            return true;
        }
    }

    public List<List<Fantasydraftresult>> getDraftTeamHistory() {
        draftTeamHistory.clear();
        for (int i = 0; i < teams.size(); i++) {
            draftTeamHistory.add(new ArrayList<Fantasydraftresult>());
        }
        List<Fantasydraftresult> draftresultbyleagueId = fantasydraftresultFacade.findDraftResultByLeagueId(league);
        Iterator<Fantasydraftresult> itr = draftresultbyleagueId.iterator();
        while (itr.hasNext()) {
            Fantasydraftresult tmp = itr.next();
            draftTeamHistory.get(teams.indexOf(tmp.getTeamId())).add(tmp);
        }
        return draftTeamHistory;
    }

    public void setDraftTeamHistory(List<List<Fantasydraftresult>> draftTeamHistory) {
        this.draftTeamHistory = draftTeamHistory;
    }

    public int getCurrentPick() {
        return currentPick;
    }

    public void setCurrentPick(int currentPick) {
        this.currentPick = currentPick;
    }

    public List<List<Fantasydraftresult>> getDraftHistory() {
        draftHistory.clear();
        for (int i = 0; i < 15; i++) {
            draftHistory.add(new ArrayList<Fantasydraftresult>());
        }
        List<Fantasydraftresult> draftresultbyleagueId = fantasydraftresultFacade.findDraftResultByLeagueId(league);
        Iterator<Fantasydraftresult> itr = draftresultbyleagueId.iterator();
        while (itr.hasNext()) {
            Fantasydraftresult tmp = itr.next();
            draftHistory.get(tmp.getRound() - 1).add(tmp);
        }
        return draftHistory;
    }

    public void setDraftHistory(List<List<Fantasydraftresult>> draftHistory) {
        this.draftHistory = draftHistory;
    }

    public List<Pair> getJoinplayerandstat() {
        joinplayerandstat.clear();
        getPlayers();
        HashMap<Integer, Nflplayerseasonstat> map = nflplayerseasonstatFacade.getStatMap();
        Iterator<Nflplayer> itr = players.iterator();
        List<Fantasydraftresult> draftresultbyleagueId = fantasydraftresultFacade.findDraftResultByLeagueId(league);
        List<Nflplayer> draftedPlayerList = new ArrayList<Nflplayer>();
        Iterator<Fantasydraftresult> it = draftresultbyleagueId.iterator();

        while (it.hasNext()) {
            draftedPlayerList.add(it.next().getPlayerId());
        }

        while (itr.hasNext()) {
            Nflplayer tmp = itr.next();
            if (!draftedPlayerList.contains(tmp)) {
                joinplayerandstat.add(new Pair(tmp, map.get(tmp.getId().intValue())));
            }
        }
        return joinplayerandstat;
    }

    public void setJoinplayerandstat(List<Pair> joinplayerandstat) {
        this.joinplayerandstat = joinplayerandstat;
    }

    public int getPickNumber() {
        pickNumber++;
        System.out.println("pickNumber: " + pickNumber);
        return pickNumber;
    }

    public void setPickNumber(int pickNumber) {
        this.pickNumber = pickNumber;
    }

    public int getDisplayPick() {
        int displayPick = pickNumber;

        return displayPick;
    }

    public int getDisplayRound() {
        int displayRound = roundNumber;
        return displayRound;
    }

    public void initiate() {
        System.out.println("initialize");
        pickNumber = 0;
        roundNumber = 0;
        FacesContext context = FacesContext.getCurrentInstance();
        HttpServletRequest request = (HttpServletRequest) context.getExternalContext().getRequest();
        AccountBean b = (AccountBean) request.getSession().getAttribute("accountBean");
        if (teams == null) {
            teams = queryTeamsInLeague(b.getCurrentLeague().getId().toString());
        }
        getRoundList();
        if (league == null) {
            league = b.getCurrentLeague();
            List<Fantasydraftresult> draftResultList = fantasydraftresultFacade.findDraftResultByLeagueId(league);
            if (draftResultList.isEmpty()) {
                currentPick = 1;
                currentRound = 1;
                numberInRound = 1;
                Iterator<List<Fantasyteam>> draftIt = roundList.iterator();
                Iterator<Fantasyteam> roundIt = draftIt.next().iterator();
                currentDraftTeam = roundIt.next();
            } else {
                Fantasydraftresult result = draftResultList.get(draftResultList.size() - 1);
                currentPick = result.getTotalPickNumber() + 1;
                currentRound = (currentPick - 1) / teams.size() + 1;
                numberInRound = (currentPick - 1) % teams.size() + 1;
                List<List<Fantasyteam>> draftList = roundList;
                List<Fantasyteam> eachRound = draftList.get(currentRound - 1);
                currentDraftTeam = eachRound.get(numberInRound - 1);
            }
        } else {
            if (league != b.getCurrentLeague()) {
                league = b.getCurrentLeague();
                List<Fantasydraftresult> draftResultList = fantasydraftresultFacade.findDraftResultByLeagueId(league);
                if (draftResultList.isEmpty()) {
                    currentPick = 1;
                    currentRound = 1;
                    numberInRound = 1;
                    Iterator<List<Fantasyteam>> draftIt = roundList.iterator();
                    Iterator<Fantasyteam> roundIt = draftIt.next().iterator();
                    currentDraftTeam = roundIt.next();
                } else {
                    Fantasydraftresult result = draftResultList.get(draftResultList.size() - 1);
                    currentPick = result.getTotalPickNumber() + 1;
                    currentRound = (currentPick - 1) / teams.size() + 1;
                    numberInRound = (currentPick - 1) % teams.size() + 1;
                    List<List<Fantasyteam>> draftList = roundList;
                    List<Fantasyteam> eachRound = draftList.get(currentRound - 1);
                    currentDraftTeam = eachRound.get(numberInRound - 1);
                }
            }
        }
    }

    public String draftPlayer() {
        draftResult = new Fantasydraftresult();
        draftResult.setLeagueId(league);
        draftResult.setFantasyPositionInRoster("BN");
        draftResult.setPlayerId(selectedPlayer);
        draftResult.setTeamId(currentDraftTeam);
        draftResult.setRound(currentRound);
        draftResult.setTotalPickNumber(currentPick);
        draftResult.setNumberInRound(numberInRound);
        fantasydraftresultFacade.create(draftResult);
        currentPick++;
        currentRound = (currentPick - 1) / teams.size() + 1;
        numberInRound = (currentPick - 1) % teams.size() + 1;
        List<List<Fantasyteam>> draftList = roundList;
        if(currentRound>15){
            gernerateMatches();
            initRoster();
            return "league";
        }else{
            List<Fantasyteam> eachRound = draftList.get(currentRound - 1);
            currentDraftTeam = eachRound.get(numberInRound - 1);
            selectedPlayer=null;
            return "draft";
        }
    }

    public void initRoster(){
        Iterator<List<Fantasydraftresult>> itr = draftHistory.iterator();
        while(itr.hasNext()){
            Iterator<Fantasydraftresult> tmpit = itr.next().iterator();
            while(tmpit.hasNext()){
                Fantasydraftresult tmp = tmpit.next();
                Fantasyrosterperweek roster = new Fantasyrosterperweek();
                roster.setFantasyPositionInRoster("BN");
                roster.setPlayerId(tmp.getPlayerId());
                roster.setTeamId(tmp.getTeamId());
                roster.setWeekId(weekFacade.getWeek("2011", "01"));
                fantasyrosterperweekFacade.create(roster);
            }
        }        
    }
    public void gernerateMatches(){
        List<Fantasymatch> matchList = new ArrayList<Fantasymatch>();
        for(int i=1;i<15;i++){
            for(int j=0;j<teams.size()/2;j++){
                Fantasymatch match = new Fantasymatch();
                if(i<10){
                    match.setWeekId(weekFacade.getWeek("2011", "0".concat(String.valueOf(i))));
                }else{
                    match.setWeekId(weekFacade.getWeek("2011", String.valueOf(i)));
                }
                match.setLeagueId(league);
                match.setHomeTeamId(teams.get(j));
                match.setHomeScore(Float.valueOf("0"));
                match.setAwayTeamId(teams.get(teams.size()-(j+1)));
                match.setAwayScore(Float.valueOf("0"));
                matchList.add(match);
            }
            Fantasyteam tempTeam = teams.get(0);
            for(int j=0;j<teams.size()-2;j++){
                teams.set(j, teams.get(j+1));
            }
            teams.set(teams.size()-2, tempTeam);
        }
        Iterator<Fantasymatch> itr = matchList.iterator();
        while(itr.hasNext()){
            Fantasymatch tmp = itr.next();
            fantasymatchFacade.create(tmp);
        }
    }
    public int getRoundNumber() {
        roundNumber++;
        roundNumber = (roundNumber - 1) % 15 + 1;
        return roundNumber;
    }

    public List<List<Fantasyteam>> getRoundList() {
        roundList.clear();
        for (int i = 0; i < round; i++) {
            if (teams == null) {
                FacesContext context = FacesContext.getCurrentInstance();
                HttpServletRequest request = (HttpServletRequest) context.getExternalContext().getRequest();
                AccountBean b = (AccountBean) request.getSession().getAttribute("accountBean");
                teams = queryTeamsInLeague(b.getCurrentLeague().getId().toString());
            }
            if (reversedTeams.isEmpty()) {
                for (int j = teams.size() - 1; j >= 0; j--) {
                    reversedTeams.add(teams.get(j));
                }
            }
            if (i % 2 == 0) {
                roundList.add(teams);
            } else {
                roundList.add(reversedTeams);
            }
        }
        return roundList;
    }

    public void setRoundList(List<List<Fantasyteam>> roundList) {
        this.roundList = roundList;
    }

    public HtmlDataTable getDataTable() {
        return dataTable;
    }

    public HtmlDataTable getRoundTable() {
        return roundTable;
    }

    public void setRoundTable(HtmlDataTable roundTable) {
        this.roundTable = roundTable;
    }

    public void setDataTable(HtmlDataTable dataTable) {
        this.dataTable = dataTable;
    }

    public int getCurrentRound() {
        return currentRound;
    }

    public void setCurrentRound(int currentRound) {
        this.currentRound = currentRound;
    }

    public Fantasyteam getCurrentDraftTeam() {
        Iterator<List<Fantasyteam>> draftIt = roundList.iterator();
        Iterator<Fantasyteam> roundIt = draftIt.next().iterator();
        currentDraftTeam = roundIt.next();
        return currentDraftTeam;
    }

    public void setCurrentDraftTeam(Fantasyteam currentDraftTeam) {
        this.currentDraftTeam = currentDraftTeam;
    }

    public Nflplayer getSelectedPlayer() {
        return selectedPlayer;
    }

    public void setSelectedPlayer(Nflplayer selectedPlayer) {
        this.selectedPlayer = selectedPlayer;
    }

    public List<Fantasyteam> getReversedTeams() {
        if (reversedTeams.isEmpty()) {
            for (int i = teams.size() - 1; i >= 0; i--) {
                reversedTeams.add(teams.get(i));
            }
        }
        return reversedTeams;
    }
    
    public void selectTeam(){
        selectedTeam = (Fantasyteam)teamTable.getRowData();
    }
    
    public void selectRound(){
        selectedRound = ((Integer)roundTable.getRowData()).intValue();
        System.out.println("row index:"+selectedRound);
    }

    public Fantasyteam getSelectedTeam() {
        return selectedTeam;
    }

    public void setSelectedTeam(Fantasyteam selectedTeam) {
        this.selectedTeam = selectedTeam;
    }
    
    public List<Fantasydraftresult> getHistorybySeletedTeam(){
        FacesContext context = FacesContext.getCurrentInstance();
        HttpServletRequest request = (HttpServletRequest) context.getExternalContext().getRequest();
        AccountBean b = (AccountBean) request.getSession().getAttribute("accountBean");
        if (league == null) {
            league = b.getCurrentLeague();
        }
        if(league==null ||selectedTeam==null){
            return null;
        }
        List<Fantasydraftresult> draftResultList = fantasydraftresultFacade.findDraftResultByLeagueIdTeamId(league,selectedTeam);
        return draftResultList;
    }
    
    public List<Fantasydraftresult> getHistorybyRound(){
        FacesContext context = FacesContext.getCurrentInstance();
        HttpServletRequest request = (HttpServletRequest) context.getExternalContext().getRequest();
        AccountBean b = (AccountBean) request.getSession().getAttribute("accountBean");
        if (league == null) {
            league = b.getCurrentLeague();
        }
        if(league==null ||selectedRound==0){
            return null;
        }
        List<Fantasydraftresult> draftResultList = fantasydraftresultFacade.findDraftResultByLeagueId(league);
        List<Fantasydraftresult> draftRoundResultList = new ArrayList<Fantasydraftresult>();
        Iterator<Fantasydraftresult> it = draftResultList.iterator();
        while(it.hasNext()){
            Fantasydraftresult tmp = it.next();
            if(tmp.getRound().intValue()==selectedRound){
                draftRoundResultList.add(tmp);
            }
        }
        return draftRoundResultList;
    }

    public int getSelectedRound() {
        return selectedRound;
    }

    public void setSelectedRound(int selectedRound) {
        this.selectedRound = selectedRound;
    }
    
    public void selectPlayer() {
        Pair p = (Pair) dataTable.getRowData();
        selectedPlayer = p.getPlayer();
        selectedplayerstat = p.getStat();
        System.out.println(selectedPlayer.getFirstName());
    }

    public void setReversedTeams(List<Fantasyteam> reversedTeams) {
        this.reversedTeams = reversedTeams;
    }

    public Nflplayerseasonstat getSelectedplayerstat() {
        return selectedplayerstat;
    }

    public void setSelectedplayerstat(Nflplayerseasonstat selectedplayerstat) {
        this.selectedplayerstat = selectedplayerstat;
    }
    private List<Fantasydraftresult> draftResults = null;
    
    public String getTeamName(){
        
        String name = teams.get(getteamname).getName();
        getteamname = (getteamname+1)%teams.size();
        return name;
    }
    
    public List<Fantasyteam> getTeams() {
        if (teams == null) {
            FacesContext context = FacesContext.getCurrentInstance();
            HttpServletRequest request = (HttpServletRequest) context.getExternalContext().getRequest();
            AccountBean b = (AccountBean) request.getSession().getAttribute("accountBean");
            teams = queryTeamsInLeague(b.getCurrentLeague().getId().toString());
        }
        return teams;
    }

    public void setTeams(List<Fantasyteam> teams) {
        this.teams = teams;
    }

    public List<Fantasydraftresult> getDraftResults() {
        if (draftResults == null) {
            draftResults = queryDraftResultsInLeague(league);
        }
        return draftResults;
    }

    public void setDraftResults(List<Fantasydraftresult> draftResults) {
        this.draftResults = draftResults;
    }

    /**
     * Creates a new instance of LeagueDraftBean
     */
    public LeagueDraftBean() {
        System.out.println("Constructed");
    }

    public List<Nflplayer> getPlayers() {
        if (players == null) {
            players = nflplayerFacade.findAll();
            System.err.println("playerList Size: " + players.size());
        }
        return players;
    }

    public Fantasyleague queryLeague() {
        String leagueId = GetLeagueIdFromContext();
        Fantasyleague fleague = fantasyleagueFacade.find(leagueId);
        return fleague;
    }

    public List<Fantasyteam> queryTeamsInLeague(String leagueId) {
        System.err.print("queryTeamsInLeague leagueId: " + leagueId);
        Fantasyleague fleague = fantasyleagueFacade.find(new Integer(leagueId));
        Collection<Fantasyteam> teamCollection = fleague.getFantasyteamCollection();
        List<Fantasyteam> teamList;
        if (teamCollection instanceof List) {
            teamList = (List) teamCollection;
        } else {
            teamList = new ArrayList(teamCollection);
        }
        return teamList;
    }

    public void insertDraft(String teamId, String playerId) {
        System.err.println("insertDraft teamId: " + teamId + ", playerId: " + playerId);
    }

    private List<Fantasydraftresult> queryDraftResultsInLeague(Fantasyleague id) {
        return fantasydraftresultFacade.findDraftResultByLeagueId(id);
    }

    public HttpSession GetSession() {
        FacesContext facesContext = FacesContext.getCurrentInstance();
        HttpSession session = (HttpSession) facesContext.getExternalContext().getSession(true);
        Enumeration e = session.getAttributeNames();
        while (e.hasMoreElements()) {
            String attr = (String) e.nextElement();
            System.err.println("      attr  = " + attr);
            Object value = session.getAttribute(attr);
            System.err.println("      value = " + value);
        }
        return session;
    }

    public String GetLeagueIdFromContext() {
        HttpSession session = GetSession();
        Fantasyleague sleague = (Fantasyleague) session.getAttribute("Fantasyleague");
        if (sleague == null) {
            return "1";
        }
        return sleague.getId().toString();
    }

    public String GetUserIdFromContext() {
        HttpSession session = GetSession();
        Fantasyuser user = (Fantasyuser) session.getAttribute("Fantasyuser");
        return user.getId().toString();
    }
}
